package com.myiam.idm.core.services.impl;

import java.util.ArrayList;
import java.util.List;

import org.hsqldb.lib.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.myiam.idm.core.model.Email;
import com.myiam.idm.core.model.Identity;
import com.myiam.idm.core.model.PhoneNumber;
import com.myiam.idm.core.services.IdentityService;
import com.myiam.idm.core.services.impl.helper.ModelToMetaModel;
import com.myiam.idm.core.syncservices.IdentitySyncServiceDelegate;
import com.myiam.idm.core.syncservices.exceptions.SyncException;
import com.myiam.idm.meta.dao.IdentityRepository;
import com.myiam.idm.meta.model.MmIdentity;


/**
 * Oversimplicatie van de werkelijkheid
 * 
 * @author smeetsst
 *
 */

@Service
@Transactional
public class IdentityServiceImpl implements IdentityService {
	
	@Autowired
	private IdentityRepository identRepo=null;
	
	@Autowired 
	private IdentitySyncServiceDelegate identityServiceDelegate = null;
	
	

	@Override
	@Transactional
	public long create(Identity identity) {
		
		
		try {
			MmIdentity metaidentity = ModelToMetaModel.identityM2MM(identity);
			
			identRepo.create(metaidentity);

			if (identityServiceDelegate != null) {
				identityServiceDelegate.syncOut(identity);
			}
			
			
		} catch (SyncException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//todo fix this
		return 0;
	}

	@Override
	public Identity getById(long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Identity> findByIndexedProperties() {
		// TODO Auto-generated method stub
		return null;
	}
	

	// TODO cleanup / inject
	public void setIdentRepo(IdentityRepository identRepo) {
		this.identRepo = identRepo;
	}
	
	
	@Override
	public List<Identity> getAll() {
		List <MmIdentity> all=this.identRepo.findAll();
		List <Identity> res = new ArrayList<Identity>(); 
				
		java.util.Iterator <MmIdentity> it = all.iterator();
		
		while(it.hasNext()) {
			res.add(ModelToMetaModel.MM2identityM(it.next()));
		}
		
		return res;
	}
}
